package com.rongke.damo.medicalrecord.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jodd.util.StringUtil;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.biz.service.MedicalRecordManager;
import com.rongke.biz.service.UserManager;
import com.rongke.commons.JsonResp;
import com.rongke.model.InspectionRecord;
import com.rongke.model.MedicalRecords;
import com.rongke.model.User;
import com.rongke.service.DictInspectionService;
import com.rongke.service.InspectionRecordService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 检查记录
 * 
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value = "/api/damo/inspectionRecord")
@Transactional
public class DamoInspectionController {
    private static final Logger     LOGGER = Logger.getLogger(DamoInspectionController.class);

    @Autowired
    private InspectionRecordService inspectionRecordService;

    @Autowired
    private DictInspectionService   dictInspectionService;

    @Autowired
    private UserManager             userManager;

    @Autowired
    private MedicalRecordManager    medicalRecordManager;

    /**
     * @添加检查记录
     * @param inspectionRecord
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addInspectionRecord(@RequestBody Map<String, String> jsonMap) {
        LOGGER.debug("add inspection in damo");

        try {
            String mobileNo = jsonMap.get("phone");
            if (StringUtil.isEmpty(mobileNo)) {
                return JsonResp.fa(null);
            }

            User user = userManager.selectOrAddUser(mobileNo);
            if (null == user) {
                return JsonResp.fa(null);
            }
            String userId = user.getUserId();

            MedicalRecords mrInfo = medicalRecordManager.selectOrAddMrByUserId(userId);
            if (null == mrInfo) {
                return JsonResp.fa(null);
            }
            long mrId = mrInfo.getId();

            //创建一个新的检查记录
            InspectionRecord irInfo = new InspectionRecord();
            irInfo.setMedicalRecordId(mrId);
            irInfo.setUserId(userId);
            irInfo.setCheckDate(jsonMap.get("checkDate"));
            irInfo.setCheckType(jsonMap.get("checkType"));
            irInfo.setCheckTypeName(jsonMap.get("checkTypeName"));
            irInfo.setPicContent(jsonMap.get("picContent"));
            irInfo.setTagInfo(jsonMap.get("tagInfo"));

            inspectionRecordService.insert(irInfo);
            JSONObject json = new JSONObject();
            json.put("id", irInfo.getId());
            return JsonResp.ok(json);
        } catch (Exception e) {
            LOGGER.error("addInspectionRecord failed", e);
            return JsonResp.fa(null);
        }
    }

    /**
     * @修改检查记录
     * @param inspectionRecord
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateInspectionRecord(@RequestBody InspectionRecord inspectionRecord) {
        LOGGER.debug("updateInspectionRecord");

        try {
            InspectionRecord irInfo = new InspectionRecord();
            irInfo.setId(inspectionRecord.getId());
            irInfo.setCheckDate(inspectionRecord.getCheckDate());
            irInfo.setCheckType(inspectionRecord.getCheckType());
            irInfo.setCheckTypeName(inspectionRecord.getCheckTypeName());
            irInfo.setPicContent(inspectionRecord.getPicContent());
            irInfo.setTagInfo(inspectionRecord.getTagInfo());
            inspectionRecord.setGmtModified(new Date());
            inspectionRecordService.updateById(inspectionRecord);

            JSONObject json = new JSONObject();
            json.put("id", inspectionRecord.getId());
            return JsonResp.ok(json);
        } catch (Exception e) {
            LOGGER.error("updateInspectionRecord failed", e);
            return JsonResp.fa(null);

        }
    }

    /**
     * 根据ID删除检查记录
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public JsonResp delInspectionRecordById(long id) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("delInspectionRecordById, id=" + id);
        }

        try {
            inspectionRecordService.deleteById(id);

            JSONObject json = new JSONObject();
            json.put("id", id);
            return JsonResp.ok(json);
        } catch (Exception e) {
            LOGGER.error("delInspectionRecordById failed, id=" + id, e);
            return JsonResp.fa(null);
        }
    }

    /**
     * @根据id查找检查记录
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectInspectionRecord(long id) {
        LOGGER.debug("查找检查记录");

        InspectionRecord inspectionRecord = inspectionRecordService.selectById(id);
        return JsonResp.ok(inspectionRecord);
    }

    @RequestMapping(value = "/selectAllByPhone", method = RequestMethod.GET)
    public JsonResp selectList(String userId) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("selectList, userId=" + userId);
        }

        try {
            MedicalRecords mr = medicalRecordManager.selectByUserId(userId);
            if (null == mr) {
                return JsonResp.ok();
            }

            long mrId = mr.getId();

            EntityWrapper<InspectionRecord> ew = new EntityWrapper<InspectionRecord>();
            ew.eq("medical_record_id", mrId);
            ew.orderBy("check_date");
            List<InspectionRecord> result = inspectionRecordService.selectList(ew);
            return JsonResp.ok(result);
        } catch (Exception e) {
            LOGGER.error("selectList failed, userId=" + userId, e);
            return JsonResp.fa(null);
        }
    }
}
